<template>
  <el-dialog
      :title="type === 'add' ? '添加角色' : '修改角色'"
      v-model="visible"
      width="800px"
      @close="handleClose"
  >
    <el-form :model="ruleForm" :rules="rules" ref="formRef" label-width="100px" class="menu-form">
      <el-form-item label="用户名" prop="username">
        <el-input type="text" v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers=updateHeader
        >
          <img v-if="ruleForm.avatar" :src="ruleForm.avatar" style="height:40px;width: 40px" class="avatar" alt=""/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <div v-if="type==='add'">
        <el-form-item label="密码" prop="password">
          <el-input type="test" max='200' v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="rank">
          <el-input type="test" max='200' v-model="ruleForm.rePassword"></el-input>
        </el-form-item>
      </div>
      <el-form-item label="昵称" prop="rank">
        <el-input type="test" max='200' v-model="ruleForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="专业" prop="major">
        <el-select
            v-model="ruleForm.major"
            placeholder="专业"
            style="width: 240px"
        >
          <el-option
              v-for="item in majorOptions"
              :key="item.value"
              :label="item.lable"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="rank">
        <el-select v-model="ruleForm.roleIds"
                   multiple
                   placeholder="Select">
          <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机账号" prop="rank">
        <el-input type="test" max='200' v-model="ruleForm.phoneNumber"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="rank">
        <el-input type="test" max='200' v-model="ruleForm.mail"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {reactive, ref, toRefs} from 'vue'
import {useRoute} from 'vue-router'
import axios from '@/utils/axios'
import {ElMessage, ElIcon} from 'element-plus'
import {majorList, updateHeader} from "@/utils";
import {Plus} from "@element-plus/icons-vue";

export default {
  name: 'DialogAddRole',
  props: {
    type: String,
    reload: Function
  },
  components: {
    ElIcon,
    Plus
  },
  setup(props) {
    const formRef = ref(null)
    const route = useRoute()
    const state = reactive({
      visible: false,
      roleOptions: [],
      majorOptions: majorList,
      ruleForm: {
        username: '',
        password: '',
        rePassword: '',
        nickname: '',
        phoneNumber: "",
        major: "",
        avatar: "",
        mail: "",
        roleIds: [],
      },
      rules: {
        name: [
          {required: 'true', message: "用户名不能会空", trigger: ['change']}
        ],
        password: [
          {required: 'true', message: '密码并不能为空', trigger: ['change']}
        ],
        rePassword: [
          {
            required: 'true', message: '密码并不能为空', trigger: ['change']
          },
        ],
        mail: [
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ]
      },
      id: ''
    })
    // 获取详情
    const getDetail = (id) => {
      axios.get(`/evaluate/user/${id}`).then(res => {
        state.ruleForm = {...res}
      })
    }
    // 获取角色列表
    const getRoleList = () => {
      axios.get("/evaluate/role").then(res => {
        state.roleOptions = res.map(role => ({id: role.id, name: role.name}))
      })
    }
    // 开启弹窗
    const open = (id) => {
      state.visible = true
      getRoleList()
      if (id) {
        state.id = id
        getDetail(id)
      } else {
        state.ruleForm = {
          username: '',
          password: '',
          rePassword: '',
          nickName: '',
          phoneNumber: "",
          avatar: "",
          mail: "",
          major: "",
          roleIds: [],
        }
      }
    }
    // 关闭弹窗
    const close = () => {
      state.visible = false
    }
    const handleClose = () => {
      formRef.value.resetFields()
    }
    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (props.type === 'add') {
            axios.post('/evaluate/user/registered', state.ruleForm).then(() => {
              ElMessage.success('添加成功')
              state.visible = false
              if (props.reload) props.reload()
            })
          } else {
            axios.put('/evaluate/user', {...state.ruleForm, id: state.id}).then(() => {
              ElMessage.success('修改成功')
              state.visible = false
              if (props.reload) props.reload()
            })
          }
        }
      })
    }
    // 上传图片
    const handleAvatarSuccess = (response, uploadFile) => {
      let src = response.data.src;
      state.ruleForm.avatar = "/api" + src
    }
    return {
      ...toRefs(state),
      open,
      close,
      formRef,
      submitForm,
      handleAvatarSuccess,
      updateHeader,
      handleClose
    }
  }
}
</script>